import { ElMessage, ElLoading } from 'element-plus';
import Vue from "./../main"
import storages from "./storage";
import { accAdd, accSub, accMul } from "./count";
var loading = null;

/**
 * open()
 * @explained 打开全屏加载
 * @param {Number} duration 加载的时间,如果不传则一直加载，需调用close()关闭
 * 
 * close()
 * @explained 关闭全屏加载
 */
export const loadingFull = {
    open: (duration) => {
        loading = ElLoading.service({
            lock: false,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        if (!!duration && (typeof duration === 'number')) {
            setTimeout(() => {
                loadingFull.close();
            }, duration)
        }
    },
    close: () => {
        loading.close();
        loading = null;
    }
}

export const goRouter = function (path, query = {}) {
    if (Vue != null) {
        const _this = Vue.config.globalProperties //vue3获取当前this
        if (!path) console.error("请传路径地址")
        _this.$router.push({ path, query })
    }
}

export function rtmpToHttp(url, type) {
    if (!url) return '';
    let str;
    switch (type) {
        case 'm3u8':
            str = url.replace('rtmp://', 'http://') + '/hls.m3u8';
            break;
        default:
            break;
    }
    return str.replace(':1935/', ':8099/');
}

/**
 * 获取一个随机字符串，hashLength个字符
 * @param {Number} hashLength 字符的个数
 * @returns {String} hashLength个字符
 */
export function createHash(hashLength) {
    hashLength = hashLength || 16;
    const hashArr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    const hashBox = [];
    const hashAll = hashArr.length;
    for (let i = 0; i < hashLength; i++) {
        let hashItem;
        if (Math.floor(Math.random() * hashAll) > hashAll / 2) {
            hashItem = hashArr[Math.floor(Math.random() * hashAll)];
        }
        else {
            hashItem = hashArr[Math.floor(Math.random() * hashAll)].toLocaleUpperCase();
        }
        hashBox.push(hashItem);
    }
    return hashBox.join('');
}

/**
 * @param {Number|String} lng 
 * @param {Number|String} lat 
 */
export function dropFrame(lng, lat, distance = 50) {
    let oneLng = 0.000001141;
    let oneLat = 0.0000009;
    let totalDistanceLng = accMul(oneLng, distance);
    let totalDistanceLat = accMul(oneLat, distance);
    let arr = [];
    arr.push([
        accSub(lng, totalDistanceLng),
        accAdd(lat, totalDistanceLat),
    ]);
    arr.push([
        accAdd(lng, totalDistanceLng),
        accAdd(lat, totalDistanceLat),
    ]);
    arr.push([
        accAdd(lng, totalDistanceLng),
        accSub(lat, totalDistanceLat),
    ]);
    arr.push([
        accSub(lng, totalDistanceLng),
        accSub(lat, totalDistanceLat),
    ]);
    arr.push([
        accSub(lng, totalDistanceLng),
        accAdd(lat, totalDistanceLat),
    ]);
    return arr;
};
export const storage = storages;

export const debounce = function (func, wait) {
    func();
    let timeout;
    return function () {
        const context = this;
        const args = [...arguments];
        if (timeout) clearTimeout(timeout);
        const callNow = !timeout;
        timeout = setTimeout(() => {
            timeout = null;
        }, wait);
        if (callNow) func.apply(context, args);
    };
}
// 节流
export function _throttle(fn, interval) {
    var last;
    var timer;
    var interval = interval || 200;
    return function () {
        var th = this;
        var args = arguments;
        var now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(function () {
                last = now;
                fn.apply(th, args);
            }, interval);
        } else {
            last = now;
            fn.apply(th, args);
        }
    }
}

// 数组对象去重 arr为二维数据 attr为属性名
export function queryArray(arr, attr) {
    let totalArr = [];
    for (var i in arr) {
        if (!Array.isArray(arr[i])) {
            console.log('type error!')
            return
        }
        totalArr.push(...arr[i]);
    }
    return totalArr.reduce((acc, curr) => {
        const index = acc.findIndex((item) => item[attr] === curr[attr])
        if (index < 0) {
            acc.push(curr)
        }
        return acc
    }, [])
}

/**
 * 查询二维数组中数组对象中重复id | type等相同的，返回一个这个二维数组的交集
 * 注意：arr暂时只支持两个数组
 * @param {Array} arr 二维数组  
 * @param {String} attr 属性名
 * @returns {Array} 返回一个数组对象
 */
export function queryArrayIntersection(arr, attr) {
    let arrRetuan = [];
    let totalArr = [];
    for (var i in arr) {
        totalArr.push(...arr[i]);
    }
    totalArr.reduce((acc, curr) => {
        const index = acc.findIndex((item) => item[attr] === curr[attr]);
        const obj = acc.find((item) => item[attr] === curr[attr]);
        if (index < 0) {
            acc.push(curr);
        };
        if (obj) {
            arrRetuan.push(obj);
        };
        return acc;
    }, []);
    return arrRetuan;
};

/**
 * @param {Array} arr1   
 * @param {Array} arr2 
 * @param {String} attr 属性名
 * @returns {Array} 返回一个数组对象
 */
export function queryArrayUse1(arr1, arr2, attr) {
    let arr = JSON.parse(JSON.stringify(arr1));
    arr1.forEach(i => {
        arr2.forEach(j => {
            if(i[attr] == j[attr]){
                arr = arr.filter(x => x[attr] != i[attr]);
            }
        })
    })
    return arr;
};

// 判断一个字符串是否是 JSON格式 
export function isJSON(str) {
    if (typeof str == 'string') {
      try {
        var obj=JSON.parse(str);
        if(typeof obj == 'object' && obj ){
            return true;
        }else{
            return false;
        }
      } catch(e) {
        // console.log('不是JSON字符串，error：'+str+'!!!'+e);
        return false;
      }
    }
}
// 字符串首字母大写
export function titleCase(str) {
    return str.slice(0,1).toUpperCase() +str.slice(1).toLowerCase();;
}